/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentResource;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.ContentResource;
import com.blandware.atleap.service.core.ContentResourceManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.UploadContentResourceForm;
import com.blandware.atleap.webapp.util.core.ResourceTypesManager;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>Updates content resource
 * </p>
 * <p><a href="UpdateContentResourceAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.27 $ $Date: 2007/04/06 10:55:54 $
 * @struts.action path="/core/contentResource/update"
 * name="uploadContentResourceForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-contentResource-update"
 * @struts.action-forward name="inputForward"
 * path="/core/contentResource/callUpdate.do"
 * redirect="true"
 * @struts.action-forward name="callUpdateImage"
 * path="/core/contentResource/image/callUpdate.do"
 * @struts.action-forward name="callUpdateFile"
 * path="/core/contentResource/file/callUpdate.do"
 * @struts.action-forward name="callUpdateDocument"
 * path="/core/contentResource/document/callUpdate.do"
 * @struts.action-forward name="listContentResources"
 * path="/core/contentResource/list.do"
 * redirect="true"
 */
public final class UpdateContentResourceAction extends BaseAction {

	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession();

        String requestUrl = (String) session.getAttribute(WebappConstants.REDIRECT_URL_KEY);
        
        if ( isCancelled(request) ) {
			resetToken(request);
			session.removeAttribute(WebappConstants.CONTENT_RESOURCE_ID_KEY);
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("listContentResources");
		}

		Long contentResourceId = null;
		if ( !GenericValidator.isBlankOrNull(request.getParameter("contentResourceId")) ) {
			contentResourceId = Long.valueOf(request.getParameter("contentResourceId"));
		} else if ( request.getAttribute(WebappConstants.CONTENT_RESOURCE_ID_KEY) != null ) {
			contentResourceId = (Long) request.getAttribute(WebappConstants.CONTENT_RESOURCE_ID_KEY);
		} else if ( session.getAttribute(WebappConstants.CONTENT_RESOURCE_ID_KEY) != null ) {
			contentResourceId = (Long) session.getAttribute(WebappConstants.CONTENT_RESOURCE_ID_KEY);
		} else {
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("listContentResources");
		}
		request.setAttribute(WebappConstants.CONTENT_RESOURCE_ID_KEY, contentResourceId);

		if ( log.isDebugEnabled() ) {
			log.debug("Updating content resource with ID=" + contentResourceId);
		}

		UploadContentResourceForm uploadContentResourceForm = (UploadContentResourceForm) form;

		ContentResourceManager contentResourceManager = (ContentResourceManager) getBean(Constants.CONTENT_RESOURCE_MANAGER_BEAN);
		ContentResource contentResource = contentResourceManager.retrieveContentResource(contentResourceId);

		if ( contentResource == null ) {
			// content resource not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("contentResourceNotFound", new ActionMessage("core.contentResource.errors.notFound"));
			saveErrors(request, errors);
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("listContentResources");
		}

		FormFile file = uploadContentResourceForm.getFile();
		String resourceType = contentResource.getType();

		//if some file was selected
		if ( file != null && file.getFileName() != null && file.getFileName().trim().length() > 0 && file.getFileSize() > 0 ) {
			String fileName = file.getFileName();
			ResourceTypesManager resourceTypesManager = ResourceTypesManager.getInstance(session.getServletContext());
            String newResourceType = resourceTypesManager.getResourceTypeByFileName(fileName);
            if (newResourceType == null) {
                newResourceType = Constants.RESOURCE_TYPE_FILE;
            }
			if ( !resourceType.equalsIgnoreCase(newResourceType) ) {            
				file.destroy();
				session.removeAttribute(WebappConstants.CONTENT_RESOURCE_ID_KEY);
				List supportedExtensions = resourceTypesManager.getResourceTypeExtensions(resourceType);
				ActionMessages errors = new ActionMessages();
                errors.add("contentResourceDifferentType", new ActionMessage("core.contentResource.errors.differentType", supportedExtensions.toString()));                
				session.setAttribute(WebappConstants.CONTENT_RESOURCE_ID_KEY, contentResourceId);
				saveErrors(request, errors);
				saveToken(request);
				return mapping.getInputForward();
			}

			session.setAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY, uploadContentResourceForm);
		} else {
			session.removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
		}

		if ( resourceType.equalsIgnoreCase(Constants.RESOURCE_TYPE_IMAGE) ) {
			return mapping.findForward("callUpdateImage");
		} else if ( resourceType.equalsIgnoreCase(Constants.RESOURCE_TYPE_FILE) ) {
			return mapping.findForward("callUpdateFile");
		} else if ( resourceType.equalsIgnoreCase(Constants.RESOURCE_TYPE_DOCUMENT) ) {
			return mapping.findForward("callUpdateDocument");
		} else {
			if ( file != null ) {
				file.destroy();
			}
			throw new Exception("Unexpected error");
		}

	}
}